package handler

import (
	"github.com/3.27/global"
	"github.com/3.27/internal/model/dao"
	"github.com/3.27/internal/model/service"
	"github.com/3.27/internal/request"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"math/rand"
	"net/http"
	"time"
)

func Login(c *gin.Context) {

	//短信验证码登录
	var loginReq request.LoginForm
	err := c.ShouldBindJSON(&loginReq)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"msg": "参数请求失败"})
		return
	}
	user, err := service.CheckMobilIsExistsByUser(loginReq.Mobile)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"msg": "手机号不存在"})
		return
	}
	key := "smsCode" + loginReq.Mobile
	code, err := global.Rdb.Get(key).Result()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"msg": "短信获取失败"})
		return
	}
	if code != loginReq.SmsCode {
		c.JSON(http.StatusBadRequest, gin.H{"msg": "短信验证码输入有误"})
		return
	}
	//手机号和短信验证码登录 不需要密码验证
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "登录成功", "data": user.ID})
	global.Rdb.Del(key) //登录成功删除验证码

}

// 短信发送
func SendCode(c *gin.Context) {

	var Req request.SendSmsCodeForm
	err := c.ShouldBindJSON(&Req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"msg": "参数请求失败"})
		return
	}
	code := rand.Intn(90000) + 10000 //模拟随机数
	key := "smsCode" + Req.Mobile
	global.Rdb.Set(key, code, time.Minute*3) //存入Redis

	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "短信发送成功", "data": code})
}

func OrderAdd(c *gin.Context) {

	order := dao.Order{
		Sn:      uuid.NewString(),
		Status:  1,
		UserId:  1,
		HotelID: 1,
		Price:   10,
		InTime:  time.Now(),
		OutTime: time.Now(),
	}
	global.DB.Create(&order)
	c.JSON(http.StatusOK, gin.H{"msg": "订单数据生成功"})
}

type Res struct {
	Sn      string    `json:"sn"`
	Name    string    `json:"name"`
	InTime  time.Time `json:"in_time"`
	OutTime time.Time `json:"out_time"`
	Price   float64   `json:"price"`
}

func OrderList(c *gin.Context) {

	var o []Res
	sql := "SELECT sn,`name`,`order`.in_time,`order`.out_time ,`order`.price  FROM `order` JOIN hotel \nON `order`.hotel_id = hotel.id\nGROUP BY `order`.sn,hotel.`name`,`order`.in_time,`order`.out_time,`order`.price"
	global.DB.Raw(sql).Scan(&o)

	c.JSON(http.StatusOK, gin.H{"code": "200", "msg": "返回信息成功", "data": o})
}
